﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CmccTool.Services
{
    internal static class DataRowExtensions
    {
        public static string SafeGetString(this DataRow row, string columnName)
        {
            // 双重检查：列存在且值不为空
            if (row.Table.Columns.Contains(columnName) &&
                !row.IsNull(columnName))
            {
                var value = row[columnName];

                // 处理DBNull和null
                if (value == null || value == DBNull.Value)
                    return string.Empty;

                // 安全转换为字符串
                return Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty;
            }
            return string.Empty;
        }

        public static int SafeGetInt(this DataRow row, string columnName)
        {
            if (row.Table.Columns.Contains(columnName) &&
                !row.IsNull(columnName) &&
                int.TryParse(row[columnName].ToString(), out int result))
            {
                return result;
            }
            return 0;
        }

        public static double SafeGetDouble(this DataRow row, string columnName)
        {
            if (row.Table.Columns.Contains(columnName) &&
                !row.IsNull(columnName) &&
                double.TryParse(row[columnName].ToString(), out double result))
            {
                return result;
            }
            return 0.0;
        }
    }
}
